import useSettingsStore from "@/stores/admin/useSettingStore";
import defaultSettings from "@/settings";
import SIcon from "@/components/public/SIcon.vue";
import lodash from "lodash";


/**
 * 渲染icon，不一定要配合【 loadIcon 】，可以单独使用
 * @param icon
 */
export const useRenderIcon = (icon) => {
    return () => {
        return h(SIcon,{icon:icon})
    }
}
// 返回项目路径
export function getNormalPath(p) {
    if (p.length === 0 || !p || p == 'undefined') {
        return p
    };
    let res = p.replace('//', '/')
    if (res[res.length - 1] === '/') {
        return res.slice(0, res.length - 1)
    }
    return res;
}
/**
 * 判断是否为json格式
 * @param str
 * @returns {boolean}
 */
export function isJSON(str) {
    if (typeof str == 'string') {
        try {
            const obj = JSON.parse(str);
            return typeof obj == 'object' && obj;
        } catch(e) {
            return false;
        }
    }
    return false;
}

/**
 * 动态标题切换
 */
export const useDynamicTitle = () => {
    const settingsStore = useSettingsStore();
    if (settingsStore.dynamicTitle) {
        document.title = settingsStore.title + " - " + defaultSettings.title;
    } else {
        document.title = settingsStore.title;
    }
};

/**
 * 根据传递的百分比点亮6个字符的HEX颜色
 * @param {string} color 要更改的颜色
 * @param {number} amount 更改颜色的量
 * @returns {string} 处理后的颜色表示为HEX
 */
export function useLighten(color, amount) {
    color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color;
    amount = Math.trunc((255 * amount) / 100);
    return `#${useAddLight(color.substring(0, 2), amount)}${useAddLight(
        color.substring(2, 4),
        amount
    )}${useAddLight(color.substring(4, 6), amount)}`;
}
/**
 * 将传递的百分比与十六进制颜色的R、G或B相加
 * @param {string} color 要更改的颜色
 * @param {number} amount 更改颜色的量
 * @returns {string} 颜色的处理部分
 */
function useAddLight(color, amount) {
    const cc = parseInt(color, 16) + amount;
    const c = cc > 255 ? 255 : cc;
    return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`;
}
/**
 * 节流
 * @param {*} fn 执行函数
 * @param {*} wait 节流时间,毫秒
 */
export const useThrottle = function (fn, wait) {
    let timer;
    return function (this_) {
        if (!timer) {
            timer = setTimeout(() => {
                fn.apply(this_, arguments)
                timer = null
            }, wait)
        }
    }
}

/**
 * 通用防抖
 *
 * @param callback 回调函数
 * @param wait     等待毫秒数
 * @param type     回调函数额外参数
 * @param options  防抖额外参数
 * @returns
 */
// prettier-ignore
export const lodashFunc = (callback, wait, type, options) => {
    return lodash.debounce(function () {
        type ? callback(type) : callback();
    }, wait, options);
};
/**
 * 判断url是否是http或https
 * @param {string} url
 * @returns {Boolean}
 */
export function isHttp(url) {
    return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
}